package com.idp.app.util;

import com.idp.app.dto.SyAjxxExportDto;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class ExcelExportUtils {
    public static void exportExcel(HttpServletResponse response, List<SyAjxxExportDto> dataList) throws IOException {
        // 创建一个新的Excel工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建一个工作表
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建标题行
        Row headerRow = sheet.createRow(0);
        String[] columns = {"ID", "案件时间", "经度", "维度", "地区编码", "详细地址", "案件类别编码", "案件类别名称", "街道", "显示内容", "类型编码", "类型名称", "图片地址", "是否删除", "商圈编码", "商圈名称"};

        for (int i = 0; i < columns.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(columns[i]);
        }

        // 填充数据
        int rowNum = 1;
        for (SyAjxxExportDto dto : dataList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(dto.getId());
            row.createCell(1).setCellValue(dto.getAjsj());
            row.createCell(2).setCellValue(dto.getJd());
            row.createCell(3).setCellValue(dto.getWd());
            row.createCell(4).setCellValue(dto.getDqbm());
            row.createCell(5).setCellValue(dto.getXxdz());
            row.createCell(6).setCellValue(dto.getAjlb());
            row.createCell(7).setCellValue(dto.getAjlbmc());
            row.createCell(8).setCellValue(dto.getJdName());
            row.createCell(9).setCellValue(dto.getXsnr());
            row.createCell(10).setCellValue(dto.getLx());
            row.createCell(11).setCellValue(dto.getTzfour());
            row.createCell(12).setCellValue(dto.getTzsix());
            row.createCell(13).setCellValue(dto.getDelFlag());
            row.createCell(14).setCellValue(dto.getSqbm());
            row.createCell(15).setCellValue(dto.getSqmc());
        }

        // 自动调整列宽
        for (int i = 0; i < columns.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=导出.xlsx");

        // 写入Excel到输出流
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();
    }
}
